import axios from "axios";
import qs from "qs";

class Http {
  constructor(base_url) {
    this.instance = axios.create({
      timeout: 1000 * 100,
      validateStatus: status => status >= 200 && status < 300, // default,
      baseURL: base_url
    });
    this.interceptors();
  }
  request({ url, method = 'GET', params = {} }) {
    const { instance } = this;
    return new Promise((resolve, reject) => {
      method = method.toLowerCase();
      const requestBody = method === 'get' ? 'params' : 'data';
      const format = method === 'get' || method === 'delete' ? params : qs.stringify(params);
      const result = instance({ url, method, [requestBody]: format});
      result.then(value => resolve(value.data), reason => console.log(reason));
    });
  }
  interceptors() {
    const { instance } = this;
    // 添加请求拦截器
    instance.interceptors.request.use((config) => {
      return config;
    }, (error) => {
      return Promise.reject(error);
    });

    // 添加响应拦截器
    instance.interceptors.response.use((response) => {
      return response;
    }, (error) => {
      return Promise.reject(error);
    });
  }
}

const instance = new Http('');
export default instance.request.bind(instance);

const AmapRequest = new Http('https://restapi.amap.com');
const Amap = AmapRequest.request.bind(AmapRequest);

export {
  Amap
}